///<reference path="shrimp.events.ts"/>
module Shrimp {
    export interface IBackground {
        color: string;
    }

    export interface IFrame {
        lastRender: Number;
    }

    export class Game {
        events: EventManager = new Shrimp.EventManager();
        canvas: HTMLCanvasElement;
        context: CanvasRenderingContext2D;
        background: IBackground;
        lastRender: number;

        constructor (selector: string, width: number = 600, height: number = 500, backgroundColor: string = "#6395ec") {
            this.canvas = <HTMLCanvasElement>document.querySelector(selector);
            this.context = this.canvas.getContext("2d");
            this.canvas.height = height;
            this.canvas.width = width;
            this.background = {
                "color": backgroundColor
            }

            this.events.on("start", function (game) {
                (<Game>game).lastRender = performance.webkitNow();
                (<any>window).webkitRequestAnimationFrame(function () {
                    (<Game>game).events.trigger("update", game);
                });
            });

            this.events.on("update", function (game, delta) {
                (<Game>game).clear();
                (<Game>game).events.trigger("draw", game);
            });

            this.events.on("draw", function (game) {
                var now = performance.webkitNow();
                var delta = (now - (<Game>game).lastRender) / 1000;
                (<Game>game).lastRender = now;

                (<any>window).webkitRequestAnimationFrame(function () {
                    (<Game>game).events.trigger("update", game, delta);
                });
            });

            this.events.trigger("start", this);
        }

        clear(): void {
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
    }
}